#!/usr/bin/env python

from subprocess import Popen
from subprocess import PIPE
import shlex
import re
import time
import tweepy
import sys
import getopt
import webbrowser
from os import system, path


waittime = 600

consumer_key = "mKTChPJ00dZ4zmx3oqsA"

consumer_secret = "OyWcKhbzagGlhwTxWMr058lmzQ4kh5L9Yr7bNXw6l0w"

file_path = 'tokens_file'

verbose = False

def usage():
	print "\nusage: %s  <options>" % sys.argv[0]
	print "\noptions:"
	print "\n -u --user				The username of your Twitter account"
	print "\n -v --verbose				Verbose mode = ON"


def login():
	global file_path
	global consumer_key
	global consumer_secret

	oauth = tweepy.OAuthHandler(consumer_key,consumer_secret)

	if not path.exists(file_path) or file_path == 'tokens_file':
		try:
			redirect_url = oauth.get_authorization_url()
		except tweepy.TweepError:
			if verbose: print 'E R R O R !: Failed to request  token. The app will close'
			sys.exit(1)
		#abrir redirect_url con el navegador determinado
		try:
			webbroser.open_new_tab(redirect_url)
		except webbroser.Error:
			if verbose: print 'E R R O R !: Failed to open the url. You must open yourself the url in your default browser'
		pin = raw_input('Enter the PIN number: ')
		try:
			oauth.get_access_token(pin)
		except tweepy.TweepError:
			if verbose: print 'E R R O R !: Failed to get the access token. The app will close.'
			sys.exit(1)
		if verbose: print 'Creating the tokens file for %s' % file_path
		try:
			file_obj = open(file_path,'w')
			file_obj.write(oauth.access_token.key+'\n'+oauth.access_token.secret+'\n')
			file_obj.close()
		except IOError:
			if verbose: print "E R R O R !: The oauth tokens won't be saved"
	else:
		oauth_tokens = {'key':'','secret':''}
		file_obj = open(file_path,'r')
		#if verbose: 
		print 'Opening file...'
		line = file_obj.read()
		line = line.split('\n')
		oauth_tokens['key'] = line[0]
		oauth_tokens['secret'] = line[1]
		oauth.set_access_token(oauth_tokens['key'],oauth_tokens['secret'])

	api = tweepy.API(oauth)
	return api

def run():
	global waittime
	api = login()
	#if verbose: 
	print 'Succesfull login! Now you can twit your song!'
	song = 'song'
	artist = 'artist'
	while True :
		song = ''
		artist = ''
		moc_command =  "mocp -i"
		try:
			result = Popen( shlex.split(moc_command) , stdout = PIPE ).communicate()[0]
			result = result.split('\n')
			if result!=[]:
				if result[0][7:] != 'STOP' and result[0][7:] != 'PAUSE':
					song = " ".join( result[4].split()[1:] )
					artist = " ".join( result[3].split()[1:] )
					if song != '' and artist != '':
						tw_msg = "#nowplaying "+song+" - "+artist+" "
						if verbose: print tw_msg
						try:
							api.update_status(tw_msg)
						except tweepy.TweepError:
							#if verbose: 
							print 'E R R O R !: A Tweep error has appeared'
							sys.exit(1)
					else:
						#if verbose: 
						print "No song or artist this time"
				else:
					print 'The Moc player is in PAUSE or STOP'
					
			time.sleep(waittime)
		except OSError, e:
			print e

def main():
	try:
		opts, args = getopt.getopt(sys.argv[1:],"hvu:",["help","verbose","user="])
		global file_path
		for opt, arg in opts:
			if opt in ("-u","--user"):
				file_path=arg
				run()
			if opt in ("-v","--verbose"): verbose=True
			if opt in ("-h","--help"): usage()
			else:
				usage()
				sys.exit(1)
	except KeyboardInterrupt:
		sys.exit(1)

if __name__ == '__main__':
	main()
	
